<?php

declare(strict_types=1);

namespace app\shop\controller\api\user;

use think\Request;
use app\shop\controller\api\ShopBase;
use sheep\exception\SheepException;
use app\shop\model\user\GoodsLog as UserGoodsLogModel;
use app\shop\model\goods\Goods;

class GoodsLog extends ShopBase
{

    public function list(Request $request, $type)
    {
        $user = $this->auth()->user();

        // 首先删除商品不存在的记录
        UserGoodsLogModel::whereNotExists(function ($query) {
            $goodsTableName = (new Goods())->db()->getTable();
            $tableName = (new UserGoodsLogModel())->db()->getTable();
            $query = $query->table($goodsTableName)->where($goodsTableName . '.id=' . $tableName . '.goods_id')->whereNull($goodsTableName . '.delete_time');   // 不查软删除的商品

            return $query;
        })->where('user_id', $user->id)->delete();

        $logs = UserGoodsLogModel::with('goods')->{$type}()->where('user_id', $user->id);

        $logs = $logs->order('update_time', 'desc')->paginate(request()->param('list_rows', 10));       // 按照更新时间排序

        return success('获取成功', $logs);
    }



    /**
     * 收藏/取消收藏
     *
     * @param Request $request
     * @return void
     */
    public function favorite(Request $request)
    {
        $user = $this->auth()->user();
        $goods_id = $request->param('goods_id');
        $goods_ids = $request->param('goods_ids');

        if ($goods_ids) {
            // 个人中心批量取消收藏
            $log = UserGoodsLogModel::favorite()->whereIn('goods_id', $goods_ids)
                ->where('user_id', $user->id)->delete();

            return success('取消收藏成功');
        }

        $log = UserGoodsLogModel::favorite()->where('goods_id', $goods_id)
                ->where('user_id', $user->id)->find();

        $favorite = false;      // 取消收藏
        if ($log) {
            // 取消收藏
            $log->delete();
        } else {
            $favorite = true;       // 收藏
            $log = new UserGoodsLogModel();
            $log->goods_id = $goods_id;
            $log->user_id = $user->id;
            $log->type = 'favorite';
            $log->save();
        }

        return success($favorite ? '收藏成功' : '取消收藏');
    }


    public function viewDel(Request $request)
    {
        $goods_id = $request->param('goods_id');    // 支持 逗号分开
        $user = $this->auth()->user();

        UserGoodsLogModel::views()->whereIn('goods_id', $goods_id)
            ->where('user_id', $user->id)->delete();

        return success('删除成功');
    }
}
